package com.wkk.controller;

import com.wkk.entity.*;
import com.wkk.service.CoachService;
import com.wkk.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
public class CourseController {

    @Autowired
    private CourseService courseService;

    @Autowired
    private CoachService coachService;

    //解决挂起的重复调用接口
    private static  List<UploadInfo> uploadInfoList = new ArrayList<>();
    //编写图片上传接口

    @GetMapping("/courseUpload")
    public String upload(){
        return "upload";
    }


    @PostMapping("/courseUpload")
    public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request){

        Integer selectId = Integer.parseInt(request.getParameter("selectId"));
        UploadInfo up =  new UploadInfo(selectId,file.getOriginalFilename());
        if(uploadInfoList.size()>0){
            for(UploadInfo uploadInfo:uploadInfoList){
                if(up.getId()==uploadInfo.getId()&&up.getFileName().equals(uploadInfo.getFileName())){
                    return "上传失败";
                }
            }
        }
        uploadInfoList.add(up);
        if(file.isEmpty()){
            return "文件上传失败";
        }

        //用于产生随机生成数,防止上传的图片出现重明问题
        // String checkCode = String.valueOf(new Random().nextInt(899999) + 100000);
        String str = (new SimpleDateFormat("yyyyMMddHHmmssSSS")).format(new Date());
        String fileName = file.getOriginalFilename();
        String[] s=fileName.split("\\.");
        str=str+"."+s[1];
        String filepath = "D:\\IdeaItem\\fitnessManagement\\fitness\\src\\main\\resources\\static\\images\\";
        File dest = new File(filepath+str);

        try{
            file.transferTo(dest);
          //  logger.info("上传成功");
            return str;//将上传成功的图片名字返回到前端页面,用于实现数据库读入
        }catch(IOException e){
         //   logger.info("上传失败");
            e.printStackTrace();
        }
        return "上传失败";
    }


    //实现精确查询
    @RequestMapping("getPageByQuery")
    public PageBean<Course> getPageByQuery(@RequestParam(value = "current",defaultValue = "1",required = false)Integer current,
                                           Course queryCourse,
                                           HttpSession session){
        session.removeAttribute("conditionInCourse");
        Course lastQuery = (Course)session.getAttribute("lastQuery");
        if(queryCourse!=null||lastQuery==null){
            session.setAttribute("lastQuery",queryCourse);
            return courseService.pageByQuery(queryCourse,current);
        }
        return courseService.pageByQuery(lastQuery,current);
    }

    @RequestMapping("getOtherPageByQuery")
    public PageBean<Course> getPageByQuery(@RequestParam(value = "current",defaultValue = "1",required = false)Integer current,
                                           HttpSession session){
        Course lastQuery = (Course)session.getAttribute("lastQuery");
        return courseService.pageByQuery(lastQuery,current);
    }


    //实现模糊查询
    @RequestMapping("getPageByCondition")
    public PageBean<Course> getPageByCondition(@RequestParam(value = "current",defaultValue = "1",required = false)Integer current,
                                                  @RequestParam(required = false,value = "condition")String condition,
                                                  HttpSession session){


        //精确查询时，移除精确查询的session,防止在查询条件下的更新和删除出现异常
        session.removeAttribute("lastQuery");
        //若是条件查询翻页，则确保上次的session还存在
        String  lastCondition = (String)session.getAttribute("conditionInCourse");
        //什么时候采用传入的condition进行查询：
        // 1.默认无条件,且之前未进行过条件查询，故：condition==null&&lastCondition==null
        // 2.新的条件传入,不管先前有什么条件都将覆盖，故：condition!=null
        // 综上所述则要么有新的条件传入，要么是无条件查询，故：condition!=null||lastCondition==null
        if(condition!=null||lastCondition==null){//若是第一次提交，则保存条件入session用于翻页时条件不丢失
            session.setAttribute("conditionInCourse",condition);
            return courseService.pageByCondition(condition,current);
        }
        //用于获取第二次以上的分页查询信息获取
        return courseService.pageByCondition(lastCondition,current);
    }

    //实现模糊查询下的删除
    @RequestMapping("deleteCourseInPage")
    public PageBean<Course> deleteCourseInPage(@RequestParam("cid")Integer cid,
                                               @RequestParam(value = "current",defaultValue = "1",required = false)Integer current,
                                               HttpSession session){
        String  lastCondition = (String)session.getAttribute("conditionInCourse");
        Course lastQuery = (Course)session.getAttribute("lastQuery");
        courseService.deleteCourseByCid(cid);
        if(lastQuery!=null){
            return courseService.pageByQuery(lastQuery,current);
        }else{
          return courseService.pageByCondition(lastCondition,current);
        }
    }

    //实现模糊查询下的更新
    @RequestMapping("updateCourseInPage")
    public PageBean<Course> updateCourseInPage(Course course,
                                               @RequestParam(value = "current",defaultValue = "1",required = false)Integer current,
                                               HttpSession session){
        String  lastCondition = (String)session.getAttribute("conditionInCourse");
        Course lastQuery = (Course)session.getAttribute("lastQuery");
        if(courseService.updateCourse(course)){
            if(lastQuery!=null){
                return courseService.pageByQuery(lastQuery,current);
            }else{
                return courseService.pageByCondition(lastCondition,current);
            }
        }
        PageBean<Course> pageBean = new PageBean<>();
        pageBean.setCurrent(0);
        return pageBean;//返回一个空页
    }


    /**
     * -实现课程添加入课表（若出现同地点同时间的课程则无法添加）
     * --教练使用接口
     * @param course 课程所有信息
     * @return
     */
    @RequestMapping("addCourse")
    public String addCourse(Course course){

        boolean temp = false;
        temp = courseService.addCourse(course);
        if(temp){
            return "1";
        }
        return "0";
    }

    /**
     * -通过课程编号删除课表中的指定课程
     * --教练使用接口
     * @param cid 课程唯一标识符
     * @return
     */
    @RequestMapping("deleteCourseByCid")
    public String deleteCourseByCid(@RequestParam("cid")Integer cid){
        if(courseService.deleteCourseByCid(cid))
            return "1";
        else
            return "0";
    }

    /**
     * -更新课表中的单个课程信息
     * --教练使用接口
     * @param updateInfo 课程所有信息
     * @return
     */
    @RequestMapping("updateCourse")
    public String updateCourseInfo(Course updateInfo){
        if(courseService.updateCourse(updateInfo))
            return "1";
        else
            return "0";
    }

    /**
     * -获取所有课的信息
     * --公共接口
     * ---预处理（实现个性化排序推荐）
     * @param model
     * @return
     */
    @RequestMapping("getCourses")
    public String getAllCourses(Model model){
        model.addAttribute("courses",courseService.selectList());
        return "1";
    }

    @RequestMapping("getCourseByCName")
    public List<Course> getCourseByCName(@RequestParam("cname")String cname){
        return courseService.selectListByMoldOrTeacher(cname);
    }

    /**
     * - 实现获取排序后的课程信息
     * @param model
     * @param value 排序方式（预约次数降序，点击次数降序）
     */
    @RequestMapping("getCourses/orderBy")
    public void getCoursesOrderBy(Model model,@RequestParam("value")String value){
        if(value.equals("searchCount")){
            //按点击量排序
            model.addAttribute("courses",courseService.orderBySearchCount());
        }else{
            //按预约量排序
            model.addAttribute("courses",courseService.orderByOrderCount());
        }
    }


    /**
     * - 通过id获取一个课程的json形式信息,并获取其预约量排名和点击量排名
     * @param cid
     * @return
     */
    @RequestMapping("getCourseByCid")
    public Course getCourseByCid(@RequestParam("cid")Integer cid,HttpSession session){
        User nowUser = (User)session.getAttribute("nowUser");
        Course course = courseService.selectOne(cid);
        //获取点击量排名
        List<Course> courses = courseService.orderBySearchCount();
        int search = 0;
        for(Course course1:courses){
            search += 1;
            if(course1.getCid()==cid){
                break;
            }
        }
        course.setSearchRanking(search);
        //获取预约量排名
        List<Course> courseList = courseService.orderByOrderCount();
        int order = 0;
        for(Course course2:courseList){
            order += 1;
            if(course2.getCid()==cid){
                break;
            }
        }
        course.setOrderRanking(order);
        courseService.updateCount("searchCount",course.getCid());//增加点击量
        courseService.addOrUpdateHistory(course,nowUser.getUid());//添加当前用户历史点击
        return course;
    }


    /**
     * - 实现教师或者课程类型的关键词查询
     * @param value 获取查询的值
     * @param model
     */
    @RequestMapping("getCoursesByTeacherOrMold")
    public String getCoursesByTeacherOrMold(@RequestParam("value")String value,Model model){
        List<Course> courses = courseService.selectListByMoldOrTeacher(value);
        if(courses.size()!=0){
          model.addAttribute("courses",courses);
           return "1";
        }
        return "不存在符合您查询条件的课程。";
    }

    /**
     * - 获取本人预约的所有课程信息
     * @param uid
     * @return
     */
    @RequestMapping("getMyCourses")
    public List<MyCourse> getMyCourses(@RequestParam("uid")Integer uid){
            return courseService.queryMyCoursesById(uid);
    }


    @RequestMapping("signInMyCourse")
    public String signInMyCourse(@RequestParam("id")Integer id){
        courseService.addOrUpdateMySign(id);
        return courseService.selectOneMC(id).getNumLast().toString();
    }
    /**
     * -获取单个预约信息
     */
    @RequestMapping("getOneMC")
    public MyCourse getOneMc(@RequestParam("id")Integer id){
        return courseService.selectOneMC(id);
    }

    /**
     * -会员端预约课程
     * @param myCourse
     * @return
     */
    @RequestMapping("addToMyCourses")
    public String addMyCourses(MyCourse myCourse){
        //加入我的订单
        courseService.addToMyCourse(myCourse,0);
        //并更新该课程的预约量
        courseService.updateCount("OrderCount",myCourse.getCid());
        return "1";
    }

    /**
     * -教练端帮学员预约课程
     * @param myCourse
     * @return
     */
    @RequestMapping("addToMyCoursesByCoach")
    public String addMyCoursesByCoach(MyCourse myCourse){
        courseService.addToMyCourse(myCourse,1);
        return "1";
    }

    /**
     * - 修改已经购买的课程信息（教练端）
     * @param myCourse
     * @return
     */
    @RequestMapping("updateMyCourse")
    public String updateMyCourse(MyCourse myCourse){
        courseService.updateMyCourse(myCourse);
        return "1";
    }

    /**
     * - 会员端取消课程预约（预删除）
     * @param id
     * @return
     */
    @RequestMapping("cancelMyCourse")
    public String cancelMyCourse(@RequestParam("id")Integer id){
        courseService.updateMyCourseState(id);
        return "1";
    }

    /**
     * - 教练端彻底删除课程（彻底删除）
     * @param id
     * @return
     */
    @RequestMapping("deleteMyCourse")
    public String deleteMyCourse(@RequestParam("id")Integer id){
        courseService.deleteMyCourseById(id);
        return "1";
    }

    /**
     * -教练端课程签退
     *
     */
    @RequestMapping("achieveCourse")
    public String achieveCourse(@RequestParam("cid")Integer cid){
        courseService.achieveCourse(cid);
        return "1";
    }


    @RequestMapping("getDesktopInfo")
    public DesktopInfo getDesktopInfo(HttpSession session){
        DesktopInfo desktopInfo = new DesktopInfo();
        User nowUser = (User)session.getAttribute("nowUser");
        desktopInfo.setCourseList(courseService.desktopAboutCourse(nowUser.getUid()));
        List<Coach> coaches = coachService.selectListOrderByRank("month",0,0);
        List<Coach> coachList = new ArrayList<>();
        for(int i =0;i<4;i++){
            coachList.add(coaches.get(i));
        }
        desktopInfo.setCoachList(coachList);
        return desktopInfo;
    }

}
